<template>
    <div class="login-bg">
        <div class="login-container">
            <div class="login-header">
                <img class="logo mr10" src="../../assets/img/logo.svg" alt="" />
                <div class="login-title">道文化管理后台</div>
            </div>
            <el-form :model="param" :rules="rules" ref="login" size="large">
                <el-form-item prop="username">
                    <el-input v-model="param.username" placeholder="用户名">
                        <template #prepend>
                            <el-icon>
                                <User />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input
                        type="password"
                        placeholder="密码"
                        v-model="param.password"
                        @keyup.enter="submitForm(login)"
                    >
                        <template #prepend>
                            <el-icon>
                                <Lock />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <!-- <div class="pwd-tips">
                    <el-checkbox class="pwd-checkbox" v-model="checked" label="记住密码" />
                    <el-link type="primary" @click="$router.push('/reset-pwd')">忘记密码</el-link>
                </div> -->
                <el-button 
                    class="login-btn" 
                    type="primary" 
                    size="large" 
                    :loading="loading"
                    @click="submitForm(login)"
                >
                    {{ loading ? '登录中...' : '登录' }}
                </el-button>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useTabsStore } from '@/store/tabs';
import { usePermissStore } from '@/store/permiss';
import { useUserStore } from '@/store/user';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { adminLogin } from '@/api/system/auth'; 

interface LoginInfo {
    username: string;
    password: string;
}

const lgStr = localStorage.getItem('login-param');
const defParam = lgStr ? JSON.parse(lgStr) : null;
const checked = ref(lgStr ? true : false);

const router = useRouter();
const param = reactive<LoginInfo>({
    username: defParam ? defParam.username : 'zhangsan',
    password: defParam ? defParam.password : '123456',
});

const rules: FormRules = {
    username: [
        {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
        },
        {
            min: 3,
            max: 20,
            message: '用户名长度在 3 到 20 个字符',
            trigger: 'blur',
        },
    ],
    password: [
        { 
            required: true, 
            message: '请输入密码', 
            trigger: 'blur' 
        },
        {
            min: 6,
            max: 20,
            message: '密码长度在 6 到 20 个字符',
            trigger: 'blur',
        },
    ],
};
const permiss = usePermissStore();
const userStore = useUserStore();
const login = ref<FormInstance>();
const loading = ref(false);

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    
    formEl.validate(async (valid: boolean) => {
        if (valid) {
            try {
                loading.value = true;
                
                // 构建登录参数
                const loginParams: any = {
                    username: param.username,
                    password: param.password,
                };
                
                const response: any = await adminLogin(loginParams);
                
                if (response.code === 200) {
                    const loginData = response.data;
                    
                    // 使用用户 Store 保存登录信息
                    userStore.setUserLogin(loginData);
                    
                    // 保存用户名到本地存储（兼容旧代码）
                    localStorage.setItem('vuems_name', param.username);
                    
                    // 设置权限
                    const keys = permiss.defaultList[param.username == 'admin' ? 'admin' : 'user'];
                    permiss.handleSet(keys);
                    
                    ElMessage.success('登录成功');
                    
                    // 记住密码功能
                    if (checked.value) {
                        localStorage.setItem('login-param', JSON.stringify(param));
                    } else {
                        localStorage.removeItem('login-param');
                    }
                    
                    // 登录成功后跳转到首页
                    router.push('/');
                } else {
                    const errorMessage = response.msg || '登录失败，请检查用户名和密码';
                    ElMessage.error(errorMessage);
                    
                    // 登录失败时清空密码字段，让用户重新输入
                    // param.password = '';
                    
                    // 登录失败时清除可能的错误状态，但不跳转页面
                    // 让用户重新输入正确的信息
                    console.log('登录失败:', response);
                }
            } catch (error) {
                console.error('登录失败:', error);
                ElMessage.error('登录失败，请检查网络连接');
                // 网络错误时不跳转页面，让用户重试
            } finally {
                loading.value = false;
            }
        } else {
            ElMessage.error('请填写正确的登录信息');
            return false;
        }
    });
};

const tabs = useTabsStore();
tabs.clearTabs();
</script>

<style scoped>
.login-bg {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100vh;
    background: url(../../assets/img/login-bg.jpg) center/cover no-repeat;
}

.login-header {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40px;
}

.logo {
    width: 35px;
}

.login-title {
    font-size: 22px;
    color: #333;
    font-weight: bold;
}

.login-container {
    width: 450px;
    border-radius: 5px;
    background: #fff;
    padding: 40px 50px 50px;
    box-sizing: border-box;
}

.pwd-tips {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    margin: -10px 0 10px;
    color: #787878;
}

.pwd-checkbox {
    height: auto;
}

.login-btn {
    display: block;
    width: 100%;
}

.login-tips {
    font-size: 12px;
    color: #999;
}

.login-text {
    display: flex;
    align-items: center;
    margin-top: 20px;
    font-size: 14px;
    color: #787878;
}
</style>
